package com.szq.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @ClassName: MyEncoder
 * @Description: 自定义编码器
 * @Author: szq
 * @Date: 2021-11-10 16:36:12
 */
public class MyEncoder extends MessageToByteEncoder {

    /**
     * 在byte开始和结束加上02 03
     * @param channelHandlerContext
     * @param in
     * @param out
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object in, ByteBuf out) throws Exception {
        String msg = in.toString();
        byte[] bytes = msg.getBytes();

        byte[] send = new byte[bytes.length + 2];
        System.arraycopy(bytes, 0, send, 1, bytes.length);
        send[0] = 0x02;
        send[send.length-1] = 0x03;

        out.writeInt(send.length);
        out.writeBytes(send);
    }
}
